package cn.huiyunche.driver.datasync.schedule;

import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.driver.service.FetchOtmOrder;
import cn.huiyunche.driver.service.OrderService;
import com.beust.jcommander.internal.Lists;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * @author : suohao
 * Date: 2019/6/24
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class GrabDayOrderSchedule implements Job, Serializable {

    /**
     * serialVersionUID
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(GrabDayOrderSchedule.class);
    private static final long serialVersionUID = -3139974185562967561L;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LOGGER.info("GrabDayOrderSchedule.execute start : {}", df.format(new Date()));
        FetchOtmOrder fetchOtmOrder = QuartzClusterFactory.fetchOtmOrder();
        OrderService orderService = QuartzClusterFactory.getOrderService();

        long current = System.currentTimeMillis();
        long zero = current-(current+ TimeZone.getDefault().getRawOffset())%(1000*3600*24);
        Date lastTime = new Date(Long.valueOf(zero));

        List<String> orderNos = fetchOtmOrder.fetchPendingOrderNo(lastTime);
        if(null==orderNos||orderNos.size()==0) {
            LOGGER.info("无最新订单");
            return;
        }

        TmsOrder tmsOrder;
        List<TmsOrder> tmsOrders = Lists.newArrayList();
        for (String orderNo:orderNos) {
            tmsOrder = fetchOtmOrder.fetchOtmOrderByOrderNo(orderNo);
            if(null==tmsOrder){
                continue;
            }
            tmsOrders.add(tmsOrder);
            try {
                orderService.handleTmsOrders(tmsOrders);
            } catch (Exception e) {
                LOGGER.error("OrderServiceImpl.handleTmsOrders is error orderNo:{},e:{}.", orderNo,e);
            }
            tmsOrders.clear();
        }
        LOGGER.info("GrabDayOrderSchedule.execute end time : {}", new Date());
    }
}
